<!-- 会员列表 -->
<template>
  <div class="memberList sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="会员名称:">
              <el-input v-model="query.memberName" placeholder="请输入会员名称" clearable/>
            </el-form-item>
            <el-form-item label="会员编号:">
              <el-input v-model="query.memberCode" placeholder="请输入会员编号" clearable/>
            </el-form-item>
            <el-form-item label="手机号:">
              <el-input v-model="query.phone" placeholder="请输入手机号" clearable/>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="会员列表数据" icon="Medal" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中" >
        <el-table ref="table" :data="dataList" max-height="493" border>
          <el-table-column label="序号" type="index" align="center" width="60"/>
          <el-table-column label="会员编号" prop="memberCode" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="会员名称" prop="memberName" align="center"></el-table-column>
          <el-table-column label="性别" prop="sex" align="center">
            <template #default="{row}">
              <span>{{ row.sex === 1 ? '男' : '女' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
          <el-table-column label="邮箱" prop="email" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="类型" prop="enableStatus" align="center">
            <template #default="{row}">
              <span v-if="row.memberType === 1">普通用户</span>
              <span v-else-if="row.memberType === 2">推广员</span>
              <span v-else>推广员+经销商</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="enableStatus" align="center">
            <template #default="{row}">
              <el-tag :type="row.enableStatus ? 'success' : 'danger'">{{ row.enableStatus ? '已启用' : '已禁用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createdTime" align="center">
            <template #default="{row}">
              <span>{{ $date(row.createdTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="240">
            <template #default="{row}">
              <el-button type="primary" icon="Edit" link @click="toUpdate(row)">修改</el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" icon="Delete" link @click="doDelete(row.memberId)">删除</el-button>
              <el-divider direction="vertical" />
              <el-button 
                :type="row.enableStatus ? 'danger' : 'success'" 
                :icon="row.enableStatus ? 'WarnTriangleFilled' : 'SuccessFilled'"
                link 
                @click="doUpdateStatus(row)">
                {{row.enableStatus ? '禁用' : '启用'}}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="show" :title="form.memberId ? '编辑' : '新增'" top="10vh" width="25%" center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="default" label-width="95px">
        <el-form-item label="名称:" prop="memberName" required>
          <el-input v-model="form.memberName" placeholder="请输入会员名称" clearable/>
        </el-form-item>
        <el-form-item label="手机号:" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" clearable/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" required>
          <el-input v-model="form.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态:" prop="enableStatus">
          <el-radio-group v-model="form.enableStatus">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSubmit">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="memberList">
  import { saveOrUpdateMemberApi, deleteMemberApi, getMemberListPagesApi, updateMemberStatusApi } from '@/api/api'
  import { regexPhone, regexMail } from '@/utils/utils'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  // 获取form表单的ref 
  const formRef = ref(null)

  const currentData = reactive({
    loading: false,
    show: false,
    query: {
      memberName: '',
      memberCode: '',
      phone: '',
      current: 1,
      size: 20,
      total: 0
    },
    dataList: [],
    form: {
      memberId: '',
      memberName: '',
      phone: '',
      email: '',
      sex: 1,
      enableStatus: 1,
      memberType: 1
    },
    rules: {
      memberName: [{ required: true, message: '请输入会员名称', trigger: ['blur', 'change'] }],
      phone: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入手机号'))
            } else {
              if(!regexPhone(value)) {
                callback(new Error('手机号必须是11位，请重新输入'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
      email: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入邮箱'))
            } else {
              if(!regexMail(value)) {
                callback(new Error('邮箱格式不对，请重新输入'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
    }
  })

  let {loading, show, query, dataList, form, rules} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getMemberListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 重置查询
  function resetSearch() {
    currentData.query.memberName = ''
    currentData.query.memberCode = ''
    currentData.query.phone = ''
    load(1)
  }

  // 新增或编辑
  function doSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认${currentData.form.memberId ? '修改' : '新增'}吗？`).then(() => {
          let loading = currentThis.$loading(`正在${currentData.form.memberId ? '修改' : '新增'}`)
          saveOrUpdateMemberApi(`${currentData.form.memberId ? 'update' : 'save'}`, currentData.form).then(res => { // 修改
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              if(currentData.form.memberId) {
                load(currentData.query.current)
              } else {
                load(1)
              }
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 修改前弹窗
  function toUpdate(e) {
    currentData.form = {...e}
    currentData.show = true
  }

  // 删除
  function doDelete(memberId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('删除中，请耐心等待')
      deleteMemberApi({ id: memberId }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 启用或者禁用
  function doUpdateStatus(e) {
    currentThis.$messageBox.confirm(`确认${e.enableStatus ? '禁用' : '启用'}吗？`).then(() => {
      let loading = currentThis.$loading(`${e.enableStatus ? '禁用' : '启用'}中，请耐心等待`)
      updateMemberStatusApi(e.memberId, e.enableStatus ? 0 : 1).then(res => {
        loading.close()
        if(res.code === '200') {
          load(currentData.query.current)
          currentThis.$message.success(res.message)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 新增编辑弹窗重置数据
  function resetForm() {
    currentData.form = {
      memberId: '',
      memberName: '',
      phone: '',
      email: '',
      sex: 1,
      enableStatus: 1,
      memberType: 1
    }
    formRef.value.resetFields()
  }

  // 分页每页显示条数改变执行
  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
  })
</script>

<style lang="less" scoped>
.memberList{
  :deep(.el-table) {
    .img-cell{
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  :deep(.el-dialog){
    .el-input, .el-textarea{
      width: 300px;
    }
    .text-center{
      text-align: center;
    }
  }
}
</style>